from django.core.paginator import Paginator
from django.http import HttpResponse
from django.shortcuts import render
from pyecharts import Bar
import jsonpickle
from collections import Counter
from django.views.decorators.csrf import csrf_exempt

import happybase

table_name = 'house-table'

connection = happybase.Connection('hbase-docker', 9090)
table = connection.table(table_name)



REMOTE_HOST = "https://pyecharts.github.io/assets/js"

def format_row(d):
    val = d.values()
    val = map(lambda x: x.decode(), val)
    val = list(val)
    return val

def bdict_dict(bd):
    newdic = {}
    for key, val in bd.items():
        key = key.decode()[key.decode().find(':')+1:]
        if (key[-1] == ':'):
            key = key[:-1]
        val = val.decode()
        newdic[key] = val
    return newdic

def getar(request):
    try:
        area = request.GET['area']
    except:
        area = '甘井子区'
    try:
        room = request.GET['room']
    except:
        room = '所有'
    return area, room

def listing(request):
    contact_list = []
    i = 1
    global connection, table
    try:
        connection.tables()
    except:
        print("connection lost")
        connection = happybase.Connection('hbase-docker', 9090)
        table = connection.table(table_name)
        print("connection establish")
    area, room = getar(request)
    for key, val in table.scan(row_prefix=area.encode()):
        temp = bdict_dict(val)
        if temp['room'] == room or room == '所有':
            temp['address'] = key.decode()
            temp['id'] = str(i)
            contact_list.append(temp)
            i = i+1
    paginator = Paginator(contact_list, 10) # Show 25 contacts per page

    page = request.GET.get('page')
    contacts = paginator.get_page(page)
    print(area)
    print(room)
    return render(request, 'detail.html', {'contacts': contacts, 'area': area, 'room': room})

def index(request):
    context = dict(
        value1 = 1,
        value2 = 2,
        value3 = 2,
    )
    return render(request, 'index.html', context)

def getanlydata(kind, arae):
    print(kind)
    a = []
    global connection, table
    try:
        connection.tables()
    except:
        print("connection lost")
        connection = happybase.Connection('hbase-docker', 9090)
        table = connection.table(table_name)
        print("connection establish")
    for x in table.scan(row_prefix=arae.encode()):
        temp = x[1][kind].decode()
        if kind == b'family:floor':
            temp = temp[:temp.find('/')]
        a.append(temp)
    b = Counter(a)
    return [{'name':key, 'value': val} for key, val in b.items()]

kind_dict = {'户型选择': b'family:room', '开发商分布': b'family:band', '楼层选择': b'family:floor'}
import json
@csrf_exempt
def analyze(request):
    area = request.POST['area']
    kind = request.POST['kind']
    kind = kind_dict[kind]
    data_list = getanlydata(kind, area)
    return HttpResponse(json.dumps(data_list))

